# coding:utf-8
import base64
from crypt import methods
import datetime
import json
import os
import random
import re
import time
from datetime import date
import uuid
from io import BytesIO

import requests
from PIL import Image
from flask import Blueprint, render_template, request, redirect, url_for, flash, session, jsonify, app, make_response, \
    current_app
from sqlalchemy import or_
from werkzeug.utils import secure_filename

import urllib
from App.ext import db, socketio
from App.validate_code import get_verify_code
from .models import User, SchoolNew,FindGood
import smtplib
from email.mime.text import MIMEText
from email.header import Header
from email.utils import formataddr
from datetime import timedelta

# 查询商品信息
from App.ShowapiRequest import ShowapiRequest
import json

school = Blueprint('school', __name__)

basepath = os.path.dirname(__file__)
image_dir = os.path.join(basepath, '../static/schoolPic/')

ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif', 'mp3'])

if not os.path.exists(image_dir):
    os.makedirs(image_dir)
else:
    pass

@school.route('/createAll')
def create():
    db.create_all()
    return 'ok'

# @school.route('/addNews', methods=['GET', 'POST'])
# def addNews():
#     if request.method == "GET":
#         username=request.args.get('username')
#         password=request.args.get('password')
#         news = SchoolNew()
#         return jsonify(news.to_json())

@school.route('/addItem/<user_id>', methods=['POST', 'GET'])
def addFindGoodDetail(user_id):
    admin_name = session['admin_name']
    admin_face = session['admin_face']
    admin_id = session.get('admin_id')
    if request.method == 'GET':
        return render_template("uploadSchoolNews.html")

# 上传信息
@school.route('/addItem/', methods=['GET', 'POST'])
def addItem():
    if request.method == 'GET':
        return render_template("uploadSchoolNews.html")
    if request.method == 'POST':
        title = request.form.get('title')
        content = request.form.get('content')
        # 上传图片
        file1 = request.files.get('file1')
        # urls将文件名添加到数据库

        print([title, content])
        print([file1])

        if not all([title, content, file1]):
            return jsonify({'Code': 500, 'msg': '请填写完整信息'})

        urls = []
        if all([file1]):
            # 保存图片
            files = [file1]
            for file in files:
                if file:
                    picname = secure_filename(file.filename)
                    urls.append('/static/schoolPic/' + picname)
                    # 上传图片
                    file.save(os.path.join(image_dir, picname))
        itemTime = time.strftime("%Y-%m-%d", time.localtime())
        db.create_all()
        print(urls)
        # 存贮到数据库
        item = SchoolNew(title=title, content=content,pic1=urls[0],time=itemTime)
        db.session.add(item)
        db.session.commit()
        return jsonify({'Code': 200, 'pic': urls})

    return jsonify({'Code': 500})

# 发布校园信息
@school.route('/schoolNewsList/', methods=['POST', 'GET'])
def addSchoolNews():
    db.create_all()
    admin_id = session['admin_id']
    admin_name = session['admin_name']
    admin_face = session['admin_face']
    print(admin_id,admin_name,admin_face)
    if not admin_id:
        print('0',admin_id,admin_name,admin_face)
        return render_template('addSchoolNews.html', admin_face='', items='')
    print('1',admin_id,admin_name,admin_face)
    items = SchoolNew.query.filter().all()
    if items:
        return render_template('addSchoolNews.html', admin_name=admin_name, admin_face=admin_face, items=items)
    print('2',admin_id,admin_name,admin_face)
    return render_template('addSchoolNews.html', admin_name=admin_name, admin_face=admin_face, items='')
        
# 删除校园信息
@school.route('/deleteItem/<item_id>', methods=['GET', 'POST'])
def deleteItem(item_id):
    item = SchoolNew.query.get(item_id)
    db.session.delete(item)
    db.session.commit()
    return redirect(url_for('school.addSchoolNews'))

@school.route('/allNews', methods=['GET', 'POST'])
def allNews():
    if request.method == "GET":
        username=request.args.get('username')
        password=request.args.get('password')
        items = SchoolNew.query.filter().all()
        res = []
        for item in items:
            res.append(item.to_json())
        return jsonify(res)

    if request.method == "POST":
        username = request.form.get('username')
        password = request.form.get('password')
        print("username:", username)
        # 校验
        # 核对用户名和密码是否一致
        user = User.query.filter_by(username=username, password=password, user_status=1).first()
        # 如果用户名和密码一致
        if user:
            # 向session中写入相应的数据
            session['user_id'] = user.user_id
            session['username'] = user.username
            session['user_pic'] = user.Icon
            msg = '* 校验通过'
            return jsonify({'code': '00000', 'msg': msg, 'data': {'succ': True, 'username': username}})
        # 如果用户名和密码不一致返回登录页面,并给提示信息
        else:
            msg = '* 用户名或者密码不一致'
            return jsonify({'code': '00001', 'msg': msg, 'data': {'succ': False, 'username': username}})